package pe.com.bbva.mantenimiento.dao.impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pe.com.bbva.mantenimiento.dao.KitDAO;
import pe.com.bbva.mantenimiento.domain.Kit;
import pe.com.bbva.util.Constantes;
import pe.com.stefanini.core.dao.GenericDAOImpl;
import pe.com.stefanini.core.exceptions.BOException;
import pe.com.stefanini.core.exceptions.DAOException;
import pe.com.stefanini.core.util.StringUtil;

@Service("kitDAO")
public class KitDAOImpl extends GenericDAOImpl<Kit> implements KitDAO{
	Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	public KitDAOImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	public List<Kit> findKits(Kit kit)throws BOException, DAOException {
		String where = "";
		if(kit.getTipoTarjeta()!= null && kit.getTipoTarjeta().getId()!=null){
			where = where + (where==""?"":" AND ") + "tipoTarjeta = " +	kit.getTipoTarjeta().getId() ;
		}
		if(kit.getTecnologia()!= null && kit.getTecnologia().getId()!=null){
			where = where + (where==""?"":" AND ") + "tecnologia = " + kit.getTecnologia().getId();
		}
		if(kit.getCodGPS()!= null && !kit.getCodGPS().equals("")){
			where = where + (where==""?"":" AND ") + "codGPS = '" +	kit.getCodGPS() + "'";
		}
		if(kit.getEstado()!= null && !kit.getEstado().equals("")){
			where = where + (where==""?"":" AND ") + "estado = '" +	kit.getEstado() + "'";
		}
		if(kit.getId()!= null && !kit.getId().equals("")){
			where = where + (where==""?"":" AND ") + "id = '" +	kit.getId() + "'";
		}
		if(kit.getApMasiva()!= null && !kit.getApMasiva().equals("")){
			where = where + (where==""?"":" AND ") + "apMasiva = " +	kit.getApMasiva() ;
		}
		if(!where.equals("")){
			where = Constantes.WHERE_CLAUSE + where;
		}
		String orders = " order by fechaCreacion desc";
		List<Kit> listaKit = super.executeQuery(Kit.class,where,orders);
		return listaKit;
	}
	
	@SuppressWarnings("deprecation")
	public Long ValidaCargaEnProceso() throws DAOException {
		Session hibernateSession = null;
		Connection con = null;
		CallableStatement cstmt =null;
		ResultSet rs  = null;		
		Long IdCarga=0L;
		try {
			hibernateSession = (Session) getHibernateTemplate().getSessionFactory().openSession();
			con = hibernateSession.connection();
			cstmt =con.prepareCall("{call TARGPS.PKG_TARGPS.PR_VALIDAR_ENPROCESO(?)}");			
			cstmt.registerOutParameter(1,oracle.jdbc.OracleTypes.VARCHAR);		
			cstmt.executeQuery();			
			IdCarga = Long.parseLong((String)cstmt.getObject(1));			
		} catch (HibernateException e) {
			logger.error(StringUtil.getStackTrace(e));
			throw new DAOException(e.getMessage());
		} catch (SQLException e) {
			logger.error(StringUtil.getStackTrace(e));
			throw new DAOException(e.getMessage());
		} catch (Exception e) {
			logger.error(StringUtil.getStackTrace(e));
			throw new DAOException(e.getMessage());
		}finally{
			try {
				if(rs!=null){
					rs.close();
				}
				if(cstmt!=null){
					cstmt.close();
				}
				hibernateSession.close();
			} catch (SQLException e) {
				throw new DAOException(e.getMessage());
			} catch (HibernateException e) {
				logger.error(StringUtil.getStackTrace(e));
				throw new DAOException(e.getMessage());
			} 
		}
		return IdCarga;
	}

	@Override
	public Date maxFechaMaterial(Long idTipoMaterial, Long idKit)
			throws BOException, DAOException {
		StringBuilder consulta = new StringBuilder();
		Date fecha = null;
		consulta.append(" SELECT MAX(FEC_INICIO+1) INICIO")
				.append(" FROM TARGPS.TTARGPS_KIT_MATERIAL ")
				.append(" WHERE 1=1 ")
				.append(" AND NID_KIT = ").append(idKit)
				.append(" AND FLG_TIPO_MATE = ").append(idTipoMaterial);
				
		List<HashMap<String, Object>> lista = null;
		lista = super.executeSQLtoMapByObject(consulta.toString());
		if(lista != null & !lista.isEmpty()){
			for (HashMap<String, Object> hashMap : lista) {
				fecha = (Date) hashMap.get("INICIO");
			}
		}
		return fecha;
	}
}